package sorted;

/**
 * @author cenghaile
 * @version 1.0
 * 2021/7/16 09:09
 **/
public class Algorithm_demo01 {
    public static void main(String[] args) {

        int[] arr = new int[]{1,2,3,4,5,6,7,8,9};
        int[] srand = srand(arr);
        System.out.println("新数组为" + srand);
        for (int i = 0; i < srand.length; i++) {
            System.out.println("第" + i + "个元素为" + srand[i]);
        }
    }

    /**
     * 随机打乱顺序，生成一个新的数组
     * @param a
     * @return
     */
    public static int[] srand(int[] a){
        int[] b = new int[a.length];
        for(int i = 0; i < a.length;i++) {
        //随机获取下标
            int tmp = (int)(Math.random()*(a.length - i)); //随机数:[ 0 ,a.length - i )
            b[i] = a[tmp];
//将此时a[tmp]的下标移动到靠后的位置
            int change = a[a.length - i - 1];
            a[a.length - i - 1] = a[tmp];
            a[tmp] = change;
        }
        return b;
    }
}
